<script setup>
import api from './api'
import { updateUserForcePwd } from "@/api/system/user";
import { getCookie, setCookie,removeCookie } from "@/utils/auth";
const route = useRoute();
const success = ref(false)
const loading = ref(false)
const subTitle = ref('')
const close = () => {
  window.close()
}

onMounted(async () => {
  const { type = 'purchase' } = route.query
  const auths = {
    // 亚马逊授权
    amazon: async () => api.authAmazon(route.query),
    // 亚马逊广告授权
    amazonAd: async () => api.adAuth(route.query),
    // 采购账号授权
    purchase: async () => api.authCallback(route.query),
    // eBay授权
    eBay: async () => api.eBayAuth(route.query),
    // 通用授权
    auth: async () => api.auth(route.query),
    //飞书授权
    feishu:async () => api.getFeishuCalendarSubscribe({code:route.query.code}),
    //修改密码授权
    changepwd: handleAuthorization
  }
  loading.value = true
  try {
    const res = await (auths[type] || auths.auth)()
    const { code, data, message } = res
    if(code === 200) {
      subTitle.value = ''
      success.value = data
    } else {
      subTitle.value = message
      success.value = false
    }
  } catch (error) {
    subTitle.value = error
    success.value = false
  }
  window.opener.postMessage(JSON.parse(JSON.stringify(success.value || {})))
  loading.value = false
})
const handleAuthorization = async ()=>{
  const authorization = getCookie("authorization");
  const authData = JSON.parse(authorization);
  const { code } = route.query
  let obj = Object.assign({},authData,{fs_rt_qrcode:code})
  const response = await updateUserForcePwd(obj)
  removeCookie('authorization')
  return response;
}
</script>

<template>
  <div class="flex justify-center mt-50px">
    <el-result :icon="loading ? 'info' : success ? 'success' : 'error'"
      :title="loading ? '正在授权...' : success ? '授权成功' : '授权失败'" :sub-title="subTitle">
      <template #extra>
        <el-button type="primary" @click="close">关闭窗口</el-button>
      </template>
    </el-result>
  </div>
</template>